package com.photoeditor.demo.ui.widget.image.watermark;

import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

/**
 * 实现类似RadioGroup选中回调的布局
 * Created by edward on 17-7-4.
 */

public class WatermarkLinearLayout extends LinearLayout {
    private OnWatermarkSelectChangeListener mLastViewListener;

    public WatermarkLinearLayout(Context context) {
        super(context);
        init(context);
    }

    public WatermarkLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public WatermarkLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    void init(Context context) {

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View view = getChildAt(i);
                if (view == null) {
                    continue;
                }
                Rect viewRect = new Rect();
                view.getGlobalVisibleRect(viewRect);
                if (view instanceof OnWatermarkSelectChangeListener
                        && viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
                    OnWatermarkSelectChangeListener currentListener = (OnWatermarkSelectChangeListener) view;
                    if (mLastViewListener != null && mLastViewListener != currentListener) {
                        mLastViewListener.onSelectChange(false);
                    }
                    currentListener.onSelectChange(true);
                    mLastViewListener = currentListener;

                    break;
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void setSelectView(View selectView) {
        View view = null;
        for (int i = 0; i < getChildCount(); i++) {
            if (getChildAt(i) == selectView) {
                view = selectView;
                break;
            }
        }
        if (view == null) {
            return;
        }
        OnWatermarkSelectChangeListener currentListener = (OnWatermarkSelectChangeListener) view;
        if (mLastViewListener != null && mLastViewListener != currentListener) {
            mLastViewListener.onSelectChange(false);
        }
        currentListener.onSelectChange(true);
        mLastViewListener = currentListener;
    }


    public interface OnWatermarkSelectChangeListener {
        void onSelectChange(boolean selected);
    }
}
